<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-12-27 10:03:28
 * @LastEditors: 李天惊 uf_lee@163.com
 * @LastEditTime: 2025-03-24 11:38:24
 * @FilePath: \global-brain\global-brain-admin\src\views\Asset\Medical\components\Edit.vue
 * Copyright (c) 2022 by 李天惊 uf_lee@163.com, All Rights Reserved. 
 * 就医记录-修改
-->
<script setup lang="ts">
import { reactive, ref, unref, watch } from 'vue'
// import { ElButton } from 'element-plus'

import { useTable } from '@/hooks/web/useTableTest'

import { ContentWrap } from '@/components/ContentWrap'
import { Form } from '@/components/Form'
// import { Table } from '@/components/Table'
// import { Dialog } from '@/components/Dialog'
// import { UploadMultiple } from '@/components/UploadMultiple'
// import MedicalUser from './MedicalUser.vue'
import EarconRefer from './EarconRefer.vue'

import { useForm } from '@/hooks/web/useForm'
import { useIcon } from '@/hooks/web/useIcon'

import { required } from '@/utils/formRules'

// import { adminFaUserListApi } from '@/api/fa/user'
import { zcAssetListApi } from '@/api/fa/earcon'
// import { adminFaPastureListApi } from '@/api/fa/pasture'
import { sysDictRelsApi } from '@/api/dict'

// 获取字典
import { useCache } from '@/hooks/web/useCache'
import { useCrudSchemas } from '@/hooks/web/useCrudSchemas'

import { ucDeptListApi } from '@/api/uc/dept'
import { zcPastureListAdminApi } from '@/api/fa/pasture'
import { zcMedicalOrderSeeApi, zcMedicalDrugDetailedListApi } from '@/api/cy/Medical'
import { spDrugListApi } from '@/api/sp/drug'
import { ElMessage, ElSelectV2 } from 'element-plus'
import { TableLxq } from '@/components/Lxq'
import { spEnclosureListApi } from '@/api/fa/enclosure'
const { wsCache } = useCache()
/****************************** 变量 start ******************************/
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

// const userInfo: any = wsCache.get('userInfo')
const dict: any = wsCache.get('dict')
const data = ref<any>({})
const dictRelsData = ref() // 联动数据
const breedSubData: any = ref([]) // 品种的枚举

const EnclosureData = ref<any[]>([]) // 栏位的枚举
const iconAdd = useIcon({ icon: 'material-symbols:add' })
const iconDel = useIcon({ icon: 'material-symbols:delete-outline' })
// const iconFile = useIcon({ icon: 'ic:outline-file-present' })

const fileRef = ref()
// const dFileRef = ref()
// const d_row = ref<any>({})
// const actionType = ref('')
// const saveLoading = ref(false)
// const d_id = ref(0) //主要用来给每个行添加一个序号，删除的时候好定位

// const dialogVisible = ref(false)
// const dialogTitle = ref('')

const rules = reactive({
  pasture_org_id: [required],
  pasture_dept_name: [required],
  symptom: [required],
  start_date: [required],
  medical_date: [required],
  type: [required]
})

// const dFile = ref([])
/****************************** 变量 end ******************************/

/****************************** 组件参数 start ******************************/
// 获取参数
const props = defineProps({
  id: {
    type: String,
    default: null
  },
  currentRow: {
    type: Object,
    default: () => null
  }
})
// console.log(props, data.value, 'id')
/****************************** 组件参数 end ******************************/
// 调用查看接口获取信息
const getMedicalOrderSee = async () => {
  if (props.id) {
    const res = await zcMedicalOrderSeeApi({ id: props.id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      data.value = await res.data

      await methodsForm.setValues(data.value)
      const json = JSON.parse(data.value.select_json)
      Search.value = {
        breed: json.breed ? json.breed : '',
        breed_sub: json.breed_sub ? json.breed_sub : '',
        earcon_code: json.earcon_code ? json.earcon_code : '',
        asset_code: json.asset_code ? json.asset_code : '',
        enclosure_id: json.enclosure_id ? json.enclosure_id : ''
      }
      console.log(json, data.value, 'res')
      DeptList(data.value.pasture_org_id)
      const Yao = await zcMedicalDrugDetailedListApi({ medical_order_id: props.id })
      if (Yao) {
        data.value.detailedData = await Yao.data
      }
    }
  } else {
    data.value.type = '1'
    data.value.detailedData = []
    await methodsForm.setValues(data.value)
  }
}

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

// 选择畜别的时候触发，处理品种类容
const breedChange = async (value) => {
  await breedGetSub(value)
  let formData = await methodsForm.getFormData()
  await methodsForm.setValues({ ...formData, breed_sub: '' })
}

const Search = ref({
  breed: '',
  breed_sub: '',
  asset_code: '',
  earcon_code: '',
  enclosure_id: ''
})
const getListAssetSelect = async () => {
  let formData: any = await methodsForm.getFormData()

  if (!!formData.pasture_org_id) {
    await getList()
  } else {
    ElMessage({
      message: '请选择牧场',
      type: 'warning'
    })
  }
}
const getListAssetReste = async () => {
  Search.value = {
    breed: '',
    breed_sub: '',
    asset_code: '',
    earcon_code: '',
    enclosure_id: ''
  }
  // await getListAsset()

  await getList()
}

const onCustomer = async (value: String) => {
  data.value.checkedAll = false
  data.value.selectData = []
  data.value.noSelectData = []
  console.log(value, 'admin_org_id')
  if (value != data.value.pasture_org_id) {
    // data.value.pasture_org_id = Number(value)
    data.value.pasture_org_id = value
    data.value.detailedData = []
    newTreeData.value = []
    data.value.pasture_dept_id = ''
    data.value.pasture_dept_name = ''
    DeptList(value)
  }
  await methodsForm.setValues(data.value)
  await getList()

  // data.value.detailedData = []
  // data.value.detailedDataEnclosure = []
}
let newTreeData = ref<any[]>([])

const DeptList = async (val) => {
  const res = await ucDeptListApi({ org_id: val })
    .catch(() => {})
    .finally(() => {
      // setTimeout(() => {
      //   loadingMain.close()
      // }, 500)
    })
  if (res) {
    newTreeData.value = res.data
    console.log(res.data, 'res')
  }
}

const schema: any = [
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListAdminApi,
      response: { count: 'count', data: 'data' },
      title: '选择创建人（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [
        { field: 'org_name', label: '牧场名称', search: { show: true } }
        // { field: 'org_id', label: '牧场编码', search: { show: true } }
      ],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer
    }
  },
  {
    field: 'pasture_dept_name',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      nameField: 'pasture_dept_name',
      data: newTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      }
    }
  },
  {
    component: 'DatePicker',
    field: 'medical_date',
    label: '就医日期',
    componentProps: {
      valueFormat: 'YYYY-MM-DD'
    }
  },
  // { component: 'InputNumber', field: 'medical_number', label: '就医数量' },
  {
    field: 'symptom',
    label: '病状记录',
    component: 'Input',
    colProps: {
      span: 12
    }
  },
  {
    field: 'note',
    label: '备注',
    component: 'Input',
    colProps: {
      span: 11
    }
  }
]
const {
  register: registerForm,
  methods: methodsForm,
  elFormRef
} = useForm({
  schema: schema
})

const getFormData = async () => {
  let formData = await methodsForm.getFormData()
  // const sku = unref(skuRef)
  // let skuData = sku?.getData()
  const file = unref(fileRef) //附件
  let fileData = file?.getData()
  // const goodsDetails = unref(goodsDetailsRef) //明细
  // let goods_details = goodsDetails?.getData()
  // let goods_tag = getGoodsTag()
  // let goods_details = data.value.goods_details
  // let goods_carousel = data.value.goods_carousel
  return {
    ...formData,
    fileData: fileData,
    selected: data.value.selected,
    detailedData: data.value.detailedData
  }
}

// const getEarconListApi = async (new_data) => {
//   let formData: any = await methods.getFormData()
//   if (!formData.customer_id) {
//     return { code: 500, count: 0, msg: '不能没有customer_id' }
//   }
//   // console.log('formData', !formData.customer_id, new_data, adminFaEarconListApi)
//   const res = await adminFaEarconListApi({ ...new_data, customer_id: formData.customer_id })
//     .catch(() => {})
//     .finally(() => {})
//   if (res) {
//     return res
//   }
// }

const getListAsset = async (a) => {
  // tableObject.tableList = []
  console.log(tableObject.paramsObj, 'date')
  // if (data.value.pasture_org_id) {
  // getList()
  return zcAssetListApi({
    ...a,
    is_die: '0',
    pasture_org_id: data.value.pasture_org_id,
    breed: Search.value.breed ? Search.value.breed : null,
    breed_sub: Search.value.breed_sub ? Search.value.breed_sub : null,
    earcon_code: Search.value.earcon_code ? Search.value.earcon_code : null,
    asset_code: Search.value.asset_code ? Search.value.asset_code : null,
    enclosure_id: Search.value.enclosure_id ? Search.value.enclosure_id : null
  })
}

/****************************** 明细配置 start ******************************/
const d_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 30
  },
  {
    field: 'id',
    label: 'ID',
    width: 100
  },
  {
    field: 'asset_code',
    label: '注射编码',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'asset_code_2',
    label: '项圈编码',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'earcon_code',
    width: 200,
    label: '耳标编码',
    search: {
      show: true
    }
  },
  {
    field: 'breed',
    label: '畜别',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.breed,
        onChange: breedChange
      },
      show: true
    }
  },
  {
    field: 'breed_sub',
    width: 200,
    label: '品种',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: breedSubData
      },
      show: true
    }
  },
  {
    field: 'enclosure_name',
    label: '栏位',
    width: 150,
    table: {
      show: true
    },
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'sex',
    label: '性别',
    width: 100,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('animal_sex', cellValue)
    }
  },
  {
    field: 'month_age',
    label: '月龄',
    width: 150
  },
  {
    field: 'purpose',
    label: '用途',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('purpose', cellValue)
    }
  }
  // {
  //   field: 'creation_time',
  //   label: '创建时间',
  //   width: 180
  // },
  // {
  //   field: 'action',
  //   width: 120,
  //   fixed: 'right',
  //   label: '操作'
  // }
])

const { allSchemas } = useCrudSchemas(d_columns)

const { register, tableObject, methods, elTableRef } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: getListAsset,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList } = methods

/****************************** 明细配置 end ******************************/

// watch(
//   () => props.currentRow,
//   (value) => {
//     if (!value) return
//     data.value = props.currentRow
//     console.log(data.value, 'ttt')
//     // if (data.value.type == 1) {
//     //   schema[7].hidden = true
//     // } else {
//     //   schema[7].hidden = false
//     // }
//     // console.log(data.value, 'waajiigjf')
//     methodsForm.setValues(data.value)
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// )
// watch(
//   () => data,
//   (value) => {
//     console.log(value.value, getFormData(), 'dataq')
//     if (!value) return
//     methodsForm.setValues(data.value)
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// )

watch(
  () => data,
  (value) => {
    if (!value) return
    methodsForm.setValues(data.value)
  },
  {
    deep: true,
    immediate: true
  }
)
watch(
  () => tableObject.tableList,
  (value) => {
    console.log('tableObject')
    if (!value) return
    if (data.value.checkedAll) {
      setTimeout(() => {
        if (data.value.noSelectData.length > 0) {
          // 去重
          console.log(tableObject.tableList, 'tableObject.tableList')
          console.log('有没有未被选中的')
          let newArr = tableObject.tableList.filter(
            (x) => !data.value.noSelectData.some((item) => x.id == item.id)
          )
          newArr.forEach((row) => {
            elTableRef.value?.toggleRowSelection(row, true)
          })
          console.log(newArr, 'newArr')
        } else {
          tableObject.tableList.forEach((row) => {
            elTableRef.value?.toggleRowSelection(row, true)
          })
        }
      }, 0)
    } else {
      if (data.value.selectData && data.value.selectData.length > 0) {
        data.value.selectData.forEach((row) => {
          elTableRef.value?.toggleRowSelection(row, true)
        })
      } else {
        data.value.selectData = []
      }
    }
  },
  {
    deep: true,
    immediate: true
  }
)
const getRowKey = (row) => {
  return row.id
}

const actionType = ref('')
const d_id = ref(0)
const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'add_d':
      d_id.value++
      data.value.detailedData.push({ d_id: d_id.value })
      // await methodsForm.setValues(data.value)
      break
    case 'del_d':
      // let row_i = data.value.detailedData.findIndex((item) => {
      //   return item.d_id == row.d_id
      // })
      data.value.detailedData.splice(row.$index, 1)
      // console.log(row, row_i, 'row')

      break
    default:
      console.log('未知类型')
  }
}

const y_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 30
  },
  // {
  //   field: 'd_id',
  //   label: 'd_id',
  //   width: 150
  // },
  {
    field: 'type',
    label: '状态',
    width: 180
  },
  {
    field: 'drug_id',
    label: '药品名称(选择)',
    width: 170
  },
  {
    field: 'medication_name',
    label: '药品名称(手填)',
    width: 150
  },
  {
    field: 'amount',
    label: '金额',
    width: 180
  },
  {
    field: 'medication_number',
    label: '数量',
    width: 180
  },
  {
    field: 'note',
    label: '备注',
    width: 150
  },
  // {
  //   field: 'creation_time',
  //   label: '创建时间',
  //   width: 180
  // },
  {
    field: 'action',
    width: 120,
    fixed: 'right',
    label: '操作'
  }
])

const www = (w) => {
  if (w.type == '1') {
    w.medication_name = null
    console.log(w, data.value, '1')
  } else if (w.type == '2') {
    w.drug_id = null
    console.log(w, data.value, '2')
  }
}
/****************************** 初始化 start ******************************/
const init = async () => {
  // 获取关联关系
  await getDictRels()
  // 调用查看接口查询数据
  await getMedicalOrderSee()
  // 跟新畜别
  if (data.value) {
    await breedGetSub(Search.value.breed)
  }
  if (props.currentRow) {
    console.log(props.currentRow, 'props')
    data.value.pasture_org_id = props.currentRow.pasture_org_id
      ? props.currentRow.pasture_org_id
      : ''
    data.value.checkedAll =
      data.value.checkedAll !== undefined
        ? data.value.checkedAll
        : JSON.parse(props.currentRow.select_json).checkedAll
    data.value.breed = JSON.parse(props.currentRow.select_json).breed
    data.value.breed_sub = JSON.parse(props.currentRow.select_json).breed_sub
    data.value.asset_code = JSON.parse(props.currentRow.select_json).asset_code
    data.value.earcon_code = JSON.parse(props.currentRow.select_json).earcon_code
    data.value.enclosure_id = JSON.parse(props.currentRow.select_json).enclosure_id
    if (data.value.breed) {
      await breedGetSub(data.value.breed)
    }
    if (data.value.checkedAll) {
      const aaa: any = []
      JSON.parse(props.currentRow.select_json).selected.forEach((element) => {
        let obj: any = {}
        obj.id = element
        aaa.push(obj)
      })
      data.value.noSelectData = data.value.noSelectData != undefined ? data.value.noSelectData : aaa
    } else if (props.currentRow.select_json) {
      const aaa: any = []
      if (JSON.parse(props.currentRow.select_json).selected) {
        JSON.parse(props.currentRow.select_json).selected.forEach((element) => {
          let obj: any = {}
          obj.id = element
          aaa.push(obj)
        })
      }
      data.value.selectData = aaa
      console.log(data.value.selectData, 'data.value.selectData', aaa)
    }
    if (props.currentRow.pasture_org_id) {
      await DeptList(props.currentRow.pasture_org_id)
    }

    //
    await getList()
  } else {
  }

  // 栏位
  const res = await spEnclosureListApi({ org_id: data.value.pasture_org_id })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    EnclosureData.value = res.data
    console.log(EnclosureData.value)
  }
}
init()
const userInfo: any = wsCache.get('userInfo')

const spDrugList = async (new_data) => {
  let formData: any = await methodsForm.getFormData()

  console.log(new_data, userInfo, formData, 'rrr')
  if (!!formData.pasture_org_id) {
    const res = await spDrugListApi({ ...new_data, pasture_org_id: formData.pasture_org_id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      return res
    }
  } else {
    ElMessage({
      message: '请选择牧场',
      type: 'warning'
    })
    return { code: 500, count: 0, msg: '不能没有customer_id' }
  }
}

defineExpose({
  methods: methods,
  elFormRef,
  getFormData,
  data,
  Search
})

const row_num = ref()
const du = (row) => {
  // row_num.value = row.d_id - 1
  console.log(row, '77')
  row_num.value = row
}
const drug = (a, b) => {
  // console.log(data.value.detailedData, row_num.value)
  // data.value.detailedData[row_num.value].medication_name = b
  console.log(a, b, '666')
  row_num.value.medication_name = a
  console.log(data.value.detailedData, '888')
}

/****************************** 初始化 end ******************************/
</script>
<template>
  <div>
    <ContentWrap title="主数据">
      <Form :rules="rules" @register="registerForm" :data="data" />
    </ContentWrap>
    <!-- <ContentWrap title="附件">
      <UploadMultiple
        ref="fileRef"
        v-model="data.fileData"
        :response="{
          url: 'file_url',
          name: 'file_name',
          file_type: 'file_type'
        }"
      />
    </ContentWrap> -->
    <ContentWrap title="明细数据">
      <div>
        <el-form :inline="true" :model="Search" class="demo-form-inline">
          <el-form-item label="资产编号">
            <el-input v-model="Search.asset_code" />
          </el-form-item>
          <el-form-item label="耳标编号">
            <el-input v-model="Search.earcon_code" />
          </el-form-item>
          <el-form-item label="畜别">
            <el-select v-model="Search.breed" placeholder="请选择" clearable @change="breedChange">
              <el-option
                v-for="item in dictRelsData"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="品种">
            <el-select v-model="Search.breed_sub" placeholder="请选择" clearable>
              <el-option
                v-for="item in breedSubData"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="栏位">
            <el-tree-select
              v-model="Search.enclosure_id"
              :props="{ value: 'id', label: 'name', children: 'children' }"
              :data="EnclosureData"
              value-key="id"
              node-key="id"
              placeholder="请选择"
              check-strictly
              :render-after-expand="false"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getListAssetSelect">查询</el-button>
            <el-button type="" @click="getListAssetReste">重置</el-button>
          </el-form-item>
        </el-form>
        <TableLxq
          v-model:pageSize="tableObject.pageSize"
          v-model:currentPage="tableObject.currentPage"
          v-model:checkedAll="data.checkedAll"
          v-model:noSelectData="data.noSelectData"
          v-model:selectData="data.selectData"
          v-model:total="tableObject.count"
          v-model:tableLen="data.number"
          :columns="allSchemas.tableColumns"
          :data="tableObject.tableList"
          :loading="tableObject.loading"
          :border="true"
          :pagination="{
            total: tableObject.count
          }"
          :row-key="getRowKey"
          :selection="true"
          highlight-current-row
          @register="register"
        />
      </div>
    </ContentWrap>

    <ContentWrap title="药品明细数据">
      <div class="mb-10px">
        <!-- <ElButton type="primary">新增行</ElButton> -->
        <ElButton circle :icon="iconAdd" @click="action('add_d')" title="新增行" />
      </div>
      <Table :columns="y_columns" :data="data.detailedData" :selection="false" :border="true">
        <template #drug_id="{ row }">
          <EarconRefer
            v-model="row.drug_id"
            :getListApi="spDrugList"
            :response="{ count: 'count', data: 'data' }"
            title="选择资产（双击选择）"
            nameField="id"
            relNameField="name"
            valueField="id"
            :crudSchemas="[
              // { field: 'is_selected', label: '是否已选', search: { show: false }, width: 120 },
              { field: 'id', label: '药品ID', search: { show: false } },
              { field: 'available_stock', label: '药品可用库存', search: { show: false } },
              { field: 'name', label: '药品名称', search: { show: true } },
              { field: 'note', label: '药品备注', search: { show: false } }
            ]"
            :modelName="row.drug_name"
            :selected="data.detailedData"
            @change="drug"
            @click="du(row)"
            v-if="row.type == 1"
          />
        </template>

        <template #medication_name="{ row }">
          <ElInput v-model="row.medication_name" v-if="row.type == 2" />
          <span></span>
        </template>

        <template #amount="{ row }">
          <ElInput v-model="row.amount" v-if="row.type == 2" />
        </template>

        <template #medication_number="{ row }">
          <ElInput v-model="row.medication_number" />
        </template>

        <template #note="{ row }">
          <ElInput v-model="row.note" />
        </template>

        <template #type2="scope">
          <ElSelectV2 v-model="scope.row.type" :options="dict.medical_drug_type" />
        </template>
        <template #type="scope">
          <el-select
            v-model="scope.row.type"
            class="m-2"
            placeholder="请选择"
            @change="www(scope.row)"
          >
            <el-option
              v-for="item in dict.medical_drug_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
        <template #creation_time="{ row }">
          <ElDatePicker v-model="row.creation_time" style="width: 150px" valueFormat="YYYY-MM-DD" />
        </template>

        <template #action="row">
          <!-- <ElButton circle :icon="iconFile" @click="action('file_d', row)" title="附件" /> -->
          <ElButton circle :icon="iconDel" @click="action('del_d', row)" title="删除行" />
        </template>
      </Table>
    </ContentWrap>
  </div>
</template>
